
#include "alta.h"
#if 0
SYS_HSE_BypassTypeDef board_hse_source(void)
{
//#ifdef BOARD_HSE_BYPASS | 1
  return SYS_HSE_BYPASS_ON;
//#else
//  return SYS_HSE_BYPASS_OFF;
//#endif
}

#define GPIO_BITS 0b1111

__attribute__((section(".text.itim")))
__attribute__( (optimize ("O3")))
void loop_gpio(volatile uint32_t *addr){
    int val = 0xff;
    while(1){
        int a = SYS->MTIME_COUNTER;
        val = *addr;
        val = *addr;
        val = *addr;
        val = *addr;
        // //val = *addr;
        // *addr = val;
        int b = a-SYS->MTIME_COUNTER;
        *(volatile int*)0x20010000 = b;
        val ^= 0xff;
    }
}

uint8_t *sram_ptr = 0x20000000;
extern int FCB_err;
uint32_t io_cmd = 1;
//__attribute__ ((weak))
int main(int argc,char**argv){
    // 现在使用最稳妥的方案.非采用HSE与PLL
    // PERIPHERAL_ENABLE(DMAC, 0);
    // DMAC_Init();
    SYS_EnableAHBClock(1);
    SYS_EnableAPBClock(APB_MASK_GPIO4);
    SYS_EnableAPBClock(APB_MASK_GPIO5);
    SYS_EnableAPBClock(APB_MASK_GPIO6);
    SYS_EnableAPBClock(APB_MASK_GPIO7);


    if(!FCB_IsInit()){
        //FCB_EnableInt(1);
    }
    if(!FCB_IsActive()){
        FCB_DeActivate();
    }

    //CB_AutoConfig
    uint32_t v1 = *(uint32_t*)0x81000030;
    uint32_t v2 = *(uint32_t*)0x81000034;
    if(v1+v2!=0xffffffff){
        v1 = *(uint32_t*)0x81000038;
        v2 = *(uint32_t*)0x8100003c;
    }
    //FCB_err = FCB_AutoDecompress(0X80036b00);
    FCB_err = FCB_AutoDecompress(v1);

    //#ifdef NO_PLL
    //参数 0:无源晶振,1为有源振荡器
    SYS_SwitchPLLClock(0);
    //#endif

    GPIO_SetOutput(GPIO4, GPIO_BITS);
    int x = 0;
    volatile uint32_t *addr = &GPIO4->GpioDIR;
    SYS->MTIME_PSC = 0xffff;
    //(void*)0x20010004
    GPIO_SetLow(GPIO4,0xff);
    GPIO_SetOutput(GPIO4, 0xff);
    GPIO_SetInput(GPIO5,0xff);
    GPIO_SetInput(GPIO6,0xff);

    while(1){
        /*
        测试slave_ahb触发读取时序
        IO4_PIN0 上升沿触发读取
        IO5      为读取数据
        IO6      为读取所需的时钟

        FPGA读取MCU SRAM所需时钟一般为11个周期

        */
        GPIO_SetHigh(GPIO4,io_cmd);
        *(volatile int*)0x20010000 = GPIO_GetValue(GPIO5,0xff);
        *(volatile int*)0x20010004 = GPIO_GetValue(GPIO7,0xff);
        *(volatile int*)0x20010008 = GPIO_GetValue(GPIO6,0xff);
        GPIO_SetLow(GPIO4,io_cmd);
    }

#if defined(TEST_CLOCK) || 1
    //loop_gpio((void*)0x41000000);
    loop_gpio((void*)0x60000004);
#endif
    while(1){
        if(x&1){
            //*(uint32_t*)0x40FFFFF0 = 0xff;
            //GPIO_SetHigh(GPIO4, GPIO_BITS);
            GPIO_SetOutput(GPIO4, 0xff);
        }
        else{
            //*(uint32_t*)0x40FFFFFC = 0xff;
            //GPIO_SetLow(GPIO4, GPIO_BITS);
            GPIO_SetInput(GPIO4, 0xff);
        }
        x++;
    }

    return 0;
}
#endif
